#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2016 lizongzhe
#
# Distributed under terms of the MIT license.
import logging
import inspect
import traceback


def auto_retry(retry):
    def retry_handle(func):
        def retry_func(*args, **kwargs):
            for i in range(retry):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    traceback.print_exc()
                    func_name = inspect.getmodule(
                        func).__name__ + "." + func.func_name
                    logger = logging.getLogger(func_name)
                    logger.debug(e)
                    logger.debug('retry {}'.format(i))
            raise Exception('retry limit error')
        return retry_func
    return retry_handle
